const express = require("express");
const router = express.Router();
const multer = require("multer");
const path = require("path");
const ResponseHelper = require("../ResponseHelper");
const fileUrl = require("../../tools/fileUrl");
const { mkdir3 } = require("../../tools");


const allowedMimetype = [
    "image/jpeg",
    "jpg",
    "jpeg",
    "image/png",
    "image/bmp",
    "gif",
    "video/x-matroska",
];

function fileFilter(req, file, cb) {
    // 这个函数应该调用 `cb` 用boolean值来指示是否应接受该文件
    if (allowedMimetype.includes(file.mimetype)) {
        //接受这个文件，使用`true`，像这样:
        cb(null, true);
    } else {
        // 拒绝这个文件，使用`false`，像这样:
        cb(new Error("Reject this type of picture"));
    }
    // 如果有问题，你可以总是这样发送一个错误:
    //cb(new Error('I don\'t have a clue!'))
}

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        const id = JSON.parse(req.params.id).id;
        const id2 = JSON.parse(req.params.id).id2;
        let uploadPath = `${fileUrl.uploadStaticPath}/${id}/${id2}`;
        console.log("uploadRemoteVideo", uploadPath);
        mkdir3(uploadPath).then(res=>{
            console.log("mkdir3",res)
            cb(null, uploadPath);
        }).catch(err=>{
            console.log("mkdir3 err",err)
        });
    },
    filename: function (req, file, cb) {
        const fileName = JSON.parse(req.params.id).name;
        let ext = path.extname(file.originalname);
        if (file.originalname === "blob" && file.mimetype != "image/bmp") {
            if (file.mimetype == "image/png") {
                ext = ".png";
            } else {
                ext = ".mp4";
            }
        } else if (file.originalname === "blob" && file.mimetype == "image/bmp") {
            ext = ".bmp";
        } else if (!ext && file.mimetype == "image/png") {
            ext = ".png";
        }
        cb(null, `${fileName}${ext}`);
    },
});

const upload = multer({
    storage: storage,
    limits: { fileSize: 1024 * 1024 * 10 },
    fileFilter,
});

router.post("/:id", upload.single("file"),async (req, res, next) => {
    console.log('uploadRoute params',req.params)
    const id = JSON.parse(req.params.id).id;
    const id2 = JSON.parse(req.params.id).id2;
    ResponseHelper.sendData(
        `http://${req.headers.host}/pubilc/uploads/${id}/${id2}/${req.file.filename}`,
        res
    );
});

module.exports = router;
